package com.china08.yxyapi.api.manage.tec.teaching.lecture.res;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.GetQuery;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.LimitOperation;
import org.springframework.data.mongodb.core.aggregation.SkipOperation;
import org.springframework.data.mongodb.core.aggregation.SortOperation;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.res.YxyResResource;
import com.china08.yxyapi.entity.es.ElasticYxyResResource;
import com.china08.yxyapi.entity.mg.lecture.YxyLecturePrePack;
import com.china08.yxyapi.entity.mg.lecture.YxyLectureRes;
import com.china08.yxyapi.model.YxyApiPageReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.YxyResResourceRepository;
import com.china08.yxyapi.repository.mg.lecture.YxyLecturePrePackRepository;
import com.china08.yxyapi.util.DateToolUtils;
import com.china08.yxyapi.util.YxyResUtil;

import io.swagger.annotations.ApiOperation;

/**
 * 老师 ---备授课--备课资源查询
 * 
 */
@CrossOrigin
@RestController
public class LectureSrhPackResController extends YxyApiBaseController {

    @Autowired
    private YxyLecturePrePackRepository yxyLecturePrePackRepository;

    @Autowired
    private YxyResUtil YxyResUtil;

    @Autowired
    private MongoTemplate mt;
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private YxyResResourceRepository YxyResResourceRepository;

    @ApiOperation(value = "备课资源查询")
    @RequestMapping(value = "/api_yw/manage/tec/teaching/lecture/res/srh/pack", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object process(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel req) {

        String userId = getProfile(request, response).getId();
        String schoolId = getProfile(request, response).getSchoolId();
        String packId = req.packId;
        String keyword = req.keyword;
        String userVIP = getProfile(request, response).getResVip();
        if (userVIP == null || userVIP.length() == 0) {
            userVIP = "false";
        }
        Pageable pageable = req.getPageable(Direction.DESC, "createdDate");
        Assert.notNull(StringUtils.defaultIfBlank(userId, null), "用户id必须");
        Assert.notNull(StringUtils.defaultIfBlank(schoolId, null), "学校id必须");

        YxyLecturePrePack lecturePrePack = yxyLecturePrePackRepository
                .findByIdAndUserIdAndSchoolIdAndIsDeleteNot(packId, userId, schoolId, 1);
        Assert.notNull(lecturePrePack, "备课包找不到了，请刷新页面");

        List<String> haveResourceIds = lecturePrePack.getResources().stream().map(x -> x.getResourceId())
                .collect(Collectors.toList());

        Criteria criteria = Criteria.where("bookcontentsId").is(req.bookcontentsId).and("userId").is(userId)
                .and("schoolId").is(schoolId).and("isDelete").is(0);
        if (StringUtils.isNotBlank(keyword)) {
            Pattern pattern = Pattern.compile("^.*" + keyword + ".*$", Pattern.CASE_INSENSITIVE);
            criteria = criteria.and("resName").regex(pattern);
        }
        if (haveResourceIds.size() > 0) {
            criteria = criteria.and("resourceId").nin(haveResourceIds);
        }
        SkipOperation operation = new SkipOperation((pageable.getPageNumber() + 1 - 1) * pageable.getPageSize());
        LimitOperation limitOperation = new LimitOperation(pageable.getPageSize());
        SortOperation sortOperation = new SortOperation(pageable.getSort());
        TypedAggregation<YxyLectureRes> aggregation = Aggregation.newAggregation(YxyLectureRes.class,
                Aggregation.match(criteria), operation, limitOperation, sortOperation);
        Query query = new Query();
        query.addCriteria(criteria);
        long total = mt.count(query, YxyLectureRes.class);
        AggregationResults<YxyLectureRes> aggregationResults = mt.aggregate(aggregation, YxyLectureRes.class);
        String schoolNick = getProfile(request, response).getSchoolName();
        List<RespModel> respModels = new ArrayList<RespModel>();
        if (aggregationResults != null) {
            RespModel respModel = null;
            for (YxyLectureRes res : aggregationResults) {
                respModel = new RespModel();
                respModel.id = res.getResourceId();
                respModel.formatId = res.getFormatId();
                respModel.author = res.getResUploader();
                respModel.dateFormat = DateToolUtils.format(res.getCreatedDate(), DateToolUtils.FORMAT_SHORT_YMD);
                respModel.title = res.getResName();
                respModel.resType = res.getResType();
                respModel.quesIds = res.getQuesIds();
                respModel.fileSize = res.getFileSize() == null ? 0 : res.getFileSize();
                respModel.userVIP = userVIP;
                YxyResResource yxyResResource = YxyResResourceRepository.findById(res.getResourceId());
                if (null != yxyResResource) {
                    respModel.isHighQualityYx = yxyResResource.getIsHighQualityYx();
                    respModel.vip = yxyResResource.getIsVip();
                } else {
                    respModel.isHighQualityYx = 0;
                    respModel.vip = false;
                }
                if (res.getResType() == 2) {
                    respModel.schoolNick = schoolNick;
                } else {
                    GetQuery getQuery = new GetQuery();
                    getQuery.setId(respModel.id);
                    ElasticYxyResResource elasticYxyResResource = elasticsearchTemplate.queryForObject(getQuery,
                            ElasticYxyResResource.class);
                    respModel.schoolNick = elasticYxyResResource != null ? elasticYxyResResource.getUploaderSchoolName()
                            : "云校";
                }
                // 资源下载
                String download = YxyResUtil.getDownloadUrl(respModel.id);
                respModel.downloadLocation = download;
                respModel.preview = YxyResUtil.getPreviewUrl(respModel.id);
                respModels.add(respModel);
            }
        }
        Page<RespModel> pageImpl = new PageImpl<RespModel>(respModels, pageable, total);
        return pageImpl;
    }

    protected static class ReqModel extends YxyApiPageReqModel {
        public String bookcontentsId;
        public String keyword;
        public String packId;

        @Override
        public void autoCheck() {
            Assert.notNull(StringUtils.defaultIfBlank(bookcontentsId, null), "目录节点不能为空!");
        }

    }

    protected static class RespModel extends YxyApiRespModel {
        public String id;
        public String formatId;
        public String title;
        public Integer resType;
        // 资源的拥有者
        public String author;
        // 收录时间
        public String dateFormat;

        public String location;

        public List<String> quesIds;

        // 下载连接
        public String downloadLocation = "";

        // 预览
        public String preview = "";

        public String schoolNick;
        public boolean vip;
        public Integer isHighQualityYx;
        public String userVIP;
        // 资源大小
        public Integer fileSize;
    }
}
